﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Dimok.Web.UI.JS.JQuery.VSDoc.js" assembly="Dimok.Web.UI" />
/// <reference path="../jquery.extentions.js" />
/// <reference name="Dimok.Web.UI.JS.MSAjaxExtentions.js" assembly="Dimok.Web.UI" />
/// <reference path="../Dimok.PageEvents.js" />
Type.registerNamespace('Dimok.Web.UI');
// Define the behavior properties.
Dimok.Web.UI.RadGridBehavior = function(element) {
  Dimok.Web.UI.RadGridBehavior.initializeBase(this, [element]);
  this._pageSizeBoxID = '';
  this._goToPageBoxID = '';
  this._pageCountLabelID = '';
  this._filterTemp = '';
  this._lastSelectedIndex = -1;
  this._filterRemoveImg = null;
  this._filtersMenuTable = null;
  this._sortBysMenuTable = null;
  this._jqdOtherFields = null;
  this._addNewRecordImg = $J();
  this._acceptNewRecordImg = $J();
  this._cancelNewRecordImg = $J();
  this._insertedRecord = null;
  this._ajaxTimeStamp = {};
  this._onRowContextMenuItemClickedDelegate = Function.createDelegate(this, this._onRowContextMenuItemClicked);
  this._initEvents(["tableDatabound", "reportDeleted", "filterChanged",
    "rowDataBound", "rowSelected", "rowDeselected", "rowDeleted", "rowBatchDeleted",
    "rowContextMenuShowed", "rowContextMenuShowing", "rowContextMenuItemClicked"]);
  Dimok.AccessorizeType(this);
}
// Create the prototype for the behavior.
Dimok.Web.UI.RadGridBehavior.prototype = {
  _grid: null, _docksID: null, _columnsMenuID: '', _filtersMenuID: '', _sortBysMenuID: '', _otherFieldsMenuID: '', _detailViewDimensions: null,
  _currentReport: '', _pageType: '', /*_clientID: '',*/_profileID: '', _clientDataKeyNames: [], _detailKeyNames: [], _detailKeys: {},
  _filterTempDefault: "1=0",
  _wsEntityType: '', _wsMethodName: "GetList", _wsMethodName_Count: '',
  _wsMethodName_Details: '', _wsMethodName_Delete: '', _wsMethodName_SetActiveRow: '',
  _rowContextMenuID: '', _inEdit: false, _contextMenuGridDataItem: null, _contextMenuColumnUniqueName: null, _metaFields: null,
  _canUpdate: false, _canDelete: false, _canInsert: false, _canHaveDocs: false,
  _activeRow: null, _activeRowKey: {}, _deselectedRow: null,
  _batchKeys: [], _selectSingleRow: true,
  _inAjax: 0, _inAjaxBatch: false, _cancelAjax: false, _executor: {}, _executorLast: { path: "", executor: null },
  // *** OnCommand Handler ***
  _onCommandHandler: function(sender, args) {
    args.set_cancel(true);
    var command = args.get_commandName();
    if (command == "Edit") return;
    if (command == "DeleteSelected") return this.deleteSelectedItems(true);
    var masterTableView = sender.get_masterTableView();
    var currentSelectedIndex = 0;
    var pageSize = masterTableView.get_pageSize();
    var pageSizer = this.get_pageSizeBox();
    pageSizer.set_maxValue(Number.MAX_VALUE);
    pageSizer.SetTextBoxValue(masterTableView.get_pageSize());
    var wsMethodName = this.get_wsMethodName();
    var docksJson = this.find_docks() ? this.find_docks().getDocksJson() : null;
    if (command == "Sort") {
      event.cancelBubble = true;
      Dimok.Web.UI.RadGridBehavior.cleanColumn(masterTableView.getColumnByUniqueName(args.get_commandArgument()));
    }
    if (!Array.contains(["Page", "Delete"], command))
      if (this.get_masterTableView().CurrentPageIndex > 0)
      return masterTableView.set_currentPageIndex(0, false, this);
    var currentPageIndex = masterTableView.get_currentPageIndex();
    var sortExpression = masterTableView.get_sortExpressions().toString();
    sortExpression = sortExpression || masterTableView.get_clientDataKeyNames().join(",");
    var filterExpressionLinq = this._cleanUpFilter().toDynamicLinq();
    var columnsArray = [];
    for (var c = 0, cc = masterTableView.get_columns(); c < cc.length; c++)
      columnsArray.push(cc[c].get_uniqueName());

    this.setCaption(command);
    this.set_inEdit(false);
    this._repaint();

    var filterTemp = !filterExpressionLinq.length && !this.get_filterTemp() ? this.get_filterTempDefault() : this.get_filterTemp();
    var context = { grid: sender, eventArgs: args, timeStamp: 0 };
    Dimok.FindWSMethod(this.get_wsMethodName(), WSA)(this.get_wsEntityType(), currentPageIndex * pageSize, pageSize,
      filterExpressionLinq, filterTemp,
      sortExpression, columnsArray, this.get_pageType(), this.get_profileID(),
			masterTableView.get_sortExpressions().toList(), masterTableView.get_filterExpressions().toList(),
			this.get_currentReport(), docksJson,
			Function.createDelegate(this, this._UpdateGrid), this.get_wsErrorDelegate(), context);
    context.timeStamp = this.set_ajaxTimeStamp(this.get_wsMethodName());
    this._showLoadPanel();
    context = { grid: sender, eventArgs: args, timeStamp: 0 };
    Dimok.FindWSMethod(this.get_wsMethodName_Count(), WSA)(this.get_wsEntityType(), filterExpressionLinq, filterTemp,
      Function.createDelegate(this, this._UpdateVirtualItemCount), this.get_wsErrorDelegate(), context);
    context.timeStamp = this.set_ajaxTimeStamp(this.get_wsMethodName_Count());
    this._showLoadPanel();
  },
  _UpdateGrid: function(result, context, methodName) {
    this._hideLoadPanel();
    if (this.get_ajaxTimeStamp(methodName) != context.timeStamp)
      return $J.bubbleTip({ html: "Canceled executor for " + methodName, element: this.get_element() });
    var grid = context.grid;
    this.set_currentReport("");
    var masterTableView = this.get_masterTableView();
    var selectedRow = masterTableView.get_selectedItems()[0];
    var activeRowKey = this.get_activeRowKey();
    grid.clearSelectedItems();
    //grid.set_activeRow(null);
    var rows = masterTableView._element.tBodies[0].rows
    rows[0].style.display = result.length > 0 && rows[0].cells.length == 1 ? "none" : ""
    var inserted = this.get_insertedRecord();
    var insertedRowIndex = -1;
    if (inserted) {
      var clientKeys = masterTableView.get_clientDataKeyNames();
      for (var r = 0; r < result.length; r++)
        if (_compare(result[r], inserted, clientKeys)) { insertedRowIndex = r; break; }
      if (insertedRowIndex < 0)
        result.push(this.get_insertedRecord());
      this.set_insertedRecord(null);
    }
    masterTableView.set_dataSource(result);
    masterTableView.dataBind();
    var ev = new Sys.EventArgs();
    ev.dataSet = result;
    this.raise_tableDatabound(this, ev);
    if (insertedRowIndex >= 0) selectedRow = masterTableView.get_dataItems()[insertedRowIndex];
    if (selectedRow) {
      if (insertedRowIndex < 0) this.clickGridDataItem(selectedRow);
      this.clickGridDataItem(selectedRow);
    } else if (masterTableView.get_dataItems().length == 1) {
      this.clickGridDataItem(this.get_MTV().get_dataItems()[0]);
    } else
      this.clickGridDataItem(_findGridDataItem(activeRowKey, masterTableView.get_dataItems()));
    if (Array.contains(["RebindGrid", "Filter"], context.eventArgs.get_commandName())) {
      Dimok.FindWSMethod("RadGrid_Report_Find", WSA)(this.get_pageType(), this.get_profileID(), Function.createDelegate(this, _cb), this.get_wsErrorDelegate());
      function _cb(result) {
        var ev = new Sys.EventArgs(); ev.get_report = function() { return result; }
        this.raise_filterChanged(ev);
      }
    }
    // *** Locals
    function _findGridDataItem(key, gridDataItems) {
      var gridDataItem = null;
      $J.each(gridDataItems, function(i, gdi) {
        if (_checkGridDataItem(gdi, key)) {
          gridDataItem = gdi;
          return false;
        }
      });
      return gridDataItem;
    }
    function _checkGridDataItem(gridDataItem, key) {
      var dataItem = gridDataItem.get_dataItem();
      var notEq = true;
      if (dataItem)
        Object.forEach(key, function(v, k) {
          if (v != dataItem[k]) return notEq = true;
          notEq = false;
        });
      return !notEq;
    }
    function _compare(o1, o2, keys) {
      for (var k = 0; k < keys.length; k++)
        if (o1[keys[k]] != o2[keys[k]]) return false;
      return true;
    }
  },
  _UpdateVirtualItemCount: function(result, context, methodName) {
    this._hideLoadPanel();
    if (this.shift_ajaxCount(methodName))
      return $J.bubbleTip({ html: "Canceled executor for " + methodName, element: this.get_element() });
    this.get_masterTableView().set_virtualItemCount(result);
    this._setMaxPage();
    //pagerCurrent.set_maxValue(Math.ceil(masterTableView.get_virtualItemCount() / masterTableView.get_pageSize()));
  },
  // *** Methods ***
  get_MTV: function() { return this.get_masterTableView(); },
  rebind: function(clearSelected) {
    if (clearSelected) this.clearSelected();
    this.get_MTV().rebind();
  },
  clearSelected: function() {
    this.get_grid().clearSelectedItems();
    this.set_activeRow(null);
  },
  getKeysByFilter: function() {
    return Dimok.Ajax({ methodName: this.get_wsMethodName() + "_Keys", wsObject: WSA },
          [this.get_wsEntityType(), this._cleanUpFilter().toDynamicLinq(), this.get_filterTemp(), this.get_MTV().get_clientDataKeyNames()]);
  },
  getGridDataItemsKeys: function(gridDataItems) {
    if (!arguments.length) gridDataItems = this.get_MTV().get_selectedItems();
    var keysArray = [];
    Array.forEach(gridDataItems, function(gdi) { keysArray.push(this.getGridDataItemKeys(gdi)); }, this);
    return keysArray;
  },
  getGridDataItemKeys: function(gridDataItem, dontAccessorize) {
    var keys = {};
    Array.forEach(this.get_MTV().get_clientDataKeyNames(), function(key) {
      keys[key] = gridDataItem ? gridDataItem.getDataKeyValue(key) : undefined;
    });
    return dontAccessorize ? keys : Dimok.$A(keys);
  },
  getDataItemKeys: function(dataItem) {
    var keys = {};
    Array.forEach(this.get_masterTableView().get_clientDataKeyNames(), function(key) {
      keys[key] = (dataItem || {})[key];
    });
    return Dimok.Accessorize(keys);
  },
  findGridDataItem: function(keys) {
    keys = Dimok.CopyData(keys, true);
    var gdi = this.get_MTV().get_dataItems();
    for (var r = 0; r < gdi.length; r++) {
      var eq = true;
      for (var k in keys)
        if (keys[k] != gdi[r].get_dataItem()[k]) { eq = false; break }
      if (eq) return gdi[r];
    }
    return null;
  },
  bindRow: function(row, gridDataItem) {
    var gdi = gridDataItem;
    var di = gdi.get_dataItem();
    var tv = gdi.get_owner();
    for (var f in row) {
      di[f] = row[f];
      var cell = tv.getCellByColumnUniqueName(gdi, f); if (!cell) continue;
      var column = tv.getColumnByUniqueName(f); if (!column) continue;
      cell.innerHTML = String.format(column._data.DataFormatString || "{0}", di[f]);
    }
  },
  // *** Event Handlers
  //  onDelete: function(sender, gridID) {
  //    $find(gridID)._onDelete(sender, event);
  //  },
  // *** delete ***
  _onDelete: function(eventArgs) {
    event.cancelBubble = true;
    return this.deleteGridDataItem($find($J(eventArgs.rawEvent.srcElement).parents("TR:first")[0].id));
  },
  deleteItemByKeys: function() {
    var keys = this.get_batchKeys().shift();
    var keysString = Sys.Serialization.JavaScriptSerializer.serialize(keys);
    if (!keys) return this._hideLoadPanel();
    Dimok.FindWSMethod(this.get_wsMethodName_Delete(), WSA)(this.get_wsEntityType(), keys,
            Function.createDelegate(this, _onSuccess),
            Function.createDelegate(this, _onError)
    );
    function _onSuccess(result) {
      _onComplete.apply(this, [{ html: keysString + "." + this.get_batchKeys().length + " left.", topFly: 0}]);
      this.raise_rowDeleted(new Dimok.Event.Loan(null, keys, this.get_batchKeys()));
    }
    function _onError(result) {
      _onComplete.apply(this, [{ error: keysString + '\n' + result.get_message()}]);
    }
    function _onComplete(bubbleSettings) {
      var tipElement = this.get_grid().get_element();
      $J.bubbleTip($J.extend({ element: tipElement }, bubbleSettings));
      if (this.get_batchKeys().length) return setTimeout(Function.createDelegate(this, this.deleteItemByKeys), 10);
      this._hideLoadPanel();
      $J.bubbleTip({ element: tipElement, html: "Batch completed.", flash: true, callback: Function.createDelegate(this, this.rebind) });
      this.raise_rowBatchDeleted();
    }
  },
  deleteGridDataItem: function(gridDataItem, inBatch) {
    var keys = this.getGridDataItemKeys(gridDataItem);
    var keysString = Sys.Serialization.JavaScriptSerializer.serialize(keys);
    if (!inBatch && !confirm("Delete row with " + keysString + "?")) return;
    Dimok.FindWSMethod(this.get_wsMethodName_Delete(), WSA)(this.get_wsEntityType(), keys,
            Function.createDelegate(this, _onSuccess),
            Function.createDelegate(this, _onError)
    );
    if (!inBatch) this._showLoadPanel();
    function _onSuccess(result) {
      _onComplete.apply(this);
      $J.bubbleTip({ element: gridDataItem.get_element(), html: keysString + " deleted.", callback: Function.createDelegate(this, _cb) });
      function _cb() {
        if (!inBatch) this.rebind(true);
        this.raise_rowDeleted(
          $J.extend(new Sys.EventArgs(), Dimok.$A({ gridDataItem: gridDataItem, keys: this.getGridDataItemKeys(gridDataItem) })));
      }
    }
    function _onError(result) {
      _onComplete.apply(this);
      $J.bubbleTip({ element: gridDataItem.get_element(), error: keysString + '\n' + result.get_message() });
    }
    function _onComplete() {
      if (!inBatch) return this._hideLoadPanel() || true;
      this._batchItemFinished(Function.createDelegate(this, this.deleteGridDataItem), gridDataItem, inBatch);
    }
    function _buildEvent(gridDataItem, keys) {
      return $J.extend(new Sys.EventArgs(), Dimok.Accessorize({ gridDataItem: gridDataItem, keys: keys }));
    }
  },
  deleteSelectedItems: function() {
    var selectedItems = this.get_grid().get_selectedItems();
    if (!selectedItems.length) {
      if (this.get_batchKeys().length) return alert("Another batch is still running.");
      if (confirm("ATTENTION!!!\n\nTo delete ALL " + this.get_MTV().get_virtualItemCount() + " items click OK.\n\n\Otherwise click Cancel and select some items first.")) {
        var batchKeys = this.getKeysByFilter();
        if (!batchKeys) return;
        if (!confirm("   !!! LAST CHANCE !!!\n\n" + batchKeys.length + " items are about to be deleted!\nMake sure you know what you doing!")) return;
        this.set_batchKeys(batchKeys);
        this._showLoadPanel();
        this.deleteItemByKeys();
      }
      return;
    }
    if (!confirm("Delete " + selectedItems.length + " selected items?")) return;
    this._showLoadPanel();
    this.deleteGridDataItem(selectedItems[0], true);
  },
  _batchItemFinished: function(batchItemActionDelegate, gridDataItem, params) {
    gridDataItem.set_selected(false);
    if (this.get_grid().get_selectedItems().length) {
      gridDataItem = this.get_grid().get_selectedItems()[0];
      var parameters = [gridDataItem];
      for (var p = 2; p < arguments.length; p++)
        parameters.push(arguments[p]);
      setTimeout(function() { batchItemActionDelegate.apply(this, parameters); }, 100);
      return false;
    }
    this._hideLoadPanel();
    this.get_grid().clearSelectedItems();
    this.set_activeRow(null);
    $J.bubbleTip({ element: this.get_element(), html: "Batch completed.", flash: true, callback: Function.createDelegate(this, this.rebind) });
    return true;
  },

  _onRowDataBound: function(sender, args) {
    this.raise_rowDataBound(args);
    var del = args.get_item().get_cell("Delete");
    if (del) {
      $clearHandlers(del);
      this.addHandlers(del, { 'click': this._onDelete }, this);
    }
    return;
    //var radTextBox1 = args.get_item().findControl("RadTextBox1"); // find control
    //radTextBox1.set_value(args.get_dataItem()["LastName"]);

    // conditional formatting
    args.get_item().get_cell("TitleOfCourtesy").style.fontWeight = (args.get_dataItem()["TitleOfCourtesy"] == "Dr.") ? "bold" : "normal";

    var sb = new Sys.StringBuilder();

    sb.appendLine("<b>RadGrid1_RowDataBound</b><br />");

    for (var item in args.get_dataItem()) {
      sb.appendLine(String.format("{0} : {1}<br />", item, args.get_dataItem()[item]));
    }

    sb.appendLine("<br />");
    sb.appendLine("<br />");

    $get("<%= Panel1.ClientID %>").innerHTML += sb.toString();
  },

  get_activeRow: function() { return this.get_grid()._activeRow; },
  set_activeRow: function(gridDataItem) {
    this.get_grid()._setActiveRow(gridDataItem);
  },
  _onRowActivated: function(sender, eventArgs) {
    //    debugger;
    //this._activeRow = this.get_activeRow() == eventArgs.get_gridDataItem() ? null : eventArgs.get_gridDataItem();
    //this.set_activeRowKey(this.get_activeRow());
  },
  _onRowActivating: function(sender, eventArgs) {
    //debugger;
    ////this.set_activeRow(eventArgs.get_gridDataItem());
    return;
    if (!eventArgs.get_domEvent()) return;
    clearTimeout(arguments.callee.procid);
    var gridItem = eventArgs.get_gridDataItem();
    if (gridItem) {
      var masterTable = this.get_masterTableView();
      while (masterTable.get_selectedItems().length > 0)
        masterTable.deselectItem(masterTable.get_selectedItems()[0].get_element());
      clearTimeout(arguments.callee.procid);
      arguments.callee.procid = setTimeout(
       Function.createDelegate(this, function() { gridItem.set_selected() }), 300);
    }
  },
  _onGridRowSelecting: function(sender, eventArgs) {
    if (eventArgs.get_gridDataItem() == this.get_deselectedRow()) {
      var This = this;
      //this.set_deselectedRow(null);
      setTimeout(function() { This.clickGridDataItem(eventArgs.get_gridDataItem(), { ctrlKey: true }); }, 100);
    }
    //eventArgs.set_cancel(same);
  },
  _onGridRowSelected: function(sender, eventArgs) {
    Dimok.Accessorize(eventArgs);
    if (this._deselectedRow == eventArgs.get_gridDataItem()) return;
    this.set_activeRowKey(eventArgs.get_dataKeyValues());
    var fetchDetails = this._jqdOtherFields && this._jqdOtherFields.dialog("isOpen");
    Dimok.FindWSMethod(this.get_wsMethodName_SetActiveRow(), WSA)(this.get_pageType(), this.get_profileID(),
      this.get_activeRowKey(), fetchDetails ? this.get_wsEntityType() : "",
      !fetchDetails ? Function.emptyFunction() :
      Function.createDelegate(this, function(dataItem) {
        this._jqdOtherFields.find("ul [DataField]").each(function() {
          this.innerHTML = this.DataFormatString ? String.localeFormat(this.DataFormatString, dataItem[this.DataField]) : dataItem[this.DataField];
        });
      }));
    this.set_deselectedRow(null);
    clearTimeout(this._onGridRowDeselected.proc);
    //this._otherFields_DataBind(eventArgs.get_gridDataItem());
    Dimok.AddProperty(eventArgs, "keys", Dimok.Accessorize(eventArgs.get_dataKeyValues(), true));
    Dimok.AddProperty(eventArgs, "detailRGEs", []);
    this.raise_rowSelected(eventArgs);
    this._setDetailRGEs(eventArgs);
  },
  _onGridRowDeselected: function(sender, eventArgs) {
    if (this._deselectedRow == eventArgs.get_gridDataItem()) return;
    this._deselectedRow = eventArgs.get_gridDataItem();
    this._onGridRowDeselected.proc = setTimeout(Function.createDelegate(this, function() {
      this.set_activeRowKey({});
      Dimok.FindWSMethod(this.get_wsMethodName_SetActiveRow(), WSA)(this.get_pageType(), this.get_profileID(), this.get_activeRowKey(), "");
      this.set_deselectedRow(null);
      this._lastSelectedIndex = eventArgs.get_itemIndexHierarchical();
      Dimok.AddProperty(eventArgs, "keys", {});
      Dimok.AddProperty(eventArgs, "detailRGEs", []);
      this.raise_rowDeselected(Dimok.Accessorize(eventArgs));
      this._setDetailRGEs(eventArgs);
    }), 200);
  },
  _setDetailRGEs: function(eventArgs) {
    Array.forEach(eventArgs.get_detailRGEs(), function(rge) { this._setDetailRGE(rge, eventArgs.get_keys()); }, this);
  },
  _setDetailRGE: function(rge, keys) {
    rge.set_detailKeys(keys);
    var filter = [];
    rge.set_filterTemp(undefined, undefined);
    Object.forEach(keys, function(keyValue, keyName) {
      rge.set_filterTemp(keyName, keyValue);
    });
  },
  _onGridRowClick: function(sender, eventArgs) {
  },

  initialize: function() {
    Dimok.Web.UI.RadGridBehavior.callBaseMethod(this, 'initialize');
    Dimok.Accessorize(this.get_metaFields());
    Sys.Application.add_load(Function.createDelegate(this, this._onLoad));
  },
  _onLoad: function(sender, args) {
    var onCommandDelegate = Function.createDelegate(this, this._onCommandHandler);
    var onColumnsMenuDelegate = Function.createDelegate(this, this._onColumnsMenuHandler);
    var onFiltersMenuDelegate = Function.createDelegate(this, this._onFiltersMenuHandler);
    Dimok.AddProperty(this.find_grid(), "extenderID", this.get_id());
    this.find_grid().add_command(onCommandDelegate);
    this.find_grid().add_columnContextMenu(onColumnsMenuDelegate);
    this.find_grid().add_columnSwapped(Function.createDelegate(this, this._columnsSwapped));

    this.find_grid().add_rowContextMenu(Function.createDelegate(this, this._onRowContextMenuHandler));
    this.find_grid().add_activeRowChanging(Function.createDelegate(this, this._onRowActivating));
    this.find_grid().add_activeRowChanged(Function.createDelegate(this, this._onRowActivated));
    this.find_grid().add_rowDataBound(Function.createDelegate(this, this._onRowDataBound));

    this.find_grid().add_rowSelecting(Function.createDelegate(this, this._onGridRowSelecting));
    this.find_grid().add_rowSelected(Function.createDelegate(this, this._onGridRowSelected));
    this.find_grid().add_rowDeselected(Function.createDelegate(this, this._onGridRowDeselected));

    this.find_grid().add_rowClick(Function.createDelegate(this, this._onGridRowClick));

    this.find_columnsMenu().add_itemClicked(Function.createDelegate(this, this._columnsChanged));
    $J("UL UL", this.get_columnsMenu()).sortable();

    this.find_filtersMenu().add_itemClicked(Function.createDelegate(this, this._filtersChanged));
    this.find_sortBysMenu().add_itemClicked(Function.createDelegate(this, this._sortBysChanged));

    this.get_pageSizeBox().add_valueChanged(Function.createDelegate(this, this.onChangePageSize));
    this.get_goToPageBox().add_valueChanged(Function.createDelegate(this, this._goToPage));
    this.setCaption();

    this.get_masterTableView().page('1');

    this._initPager();

    //setTimeout(function() { $find(gridID).get_masterTableView().page('1'); }, 500);
  },
  _abortExecutor: function(path) {
    if (this.get_executor(path) && this.get_executor(path).get_started()) {
      this.get_executor(path).abort();
    }
  },
  _initPager: function() {
    var mtv = this.get_masterTableView();
    var pageCurrLable = $J(".PagerRight_Office2007 B:eq(1)", this.get_element())[0];
    if (!$get(mtv.get_id() + "CPI")) alert("CPI not found.");
    pageCurrLable.parentElement.insertBefore($get(this.get_goToPageBox()._wrapperElementID), pageCurrLable);
    pageCurrLable.style.display = 'none';
    var jqPagerContainer = $J(pageCurrLable).parents('div:first').parent('td');
    jqPagerContainer.children('div:first').remove();
    var jqLast = jqPagerContainer.children('div:last');
    var horMargin = 3;

    jqLast.append("<img src='/images/buttons/Refresh-Arrows1.gif' style='margin:0px' title='Refresh List' />");
    this._$refreshImg = jqLast.children("img:last");
    this.addHandlers(this._$refreshImg[0], { 'click': Function.createDelegate(mtv, mtv.rebind) }, this);

    jqLast.append("<img src='/images/buttons/Refresh-ArrowsA.gif' style='margin:0px' title='Stop Process' />");
    this._$refreshImgA = jqLast.children("img:last");
    this.addHandlers(this._$refreshImgA, { 'click': function() { this.set_cancelAjax(true); } }, this);

    jqLast.append("<img src='/images/buttons/FilterRemove.gif' style='margin:0px " + horMargin + "px' title='Clear Filter' />");
    this._filterRemoveImg = jqLast.children("img:last")[0];
    this.addHandlers(this._filterRemoveImg, { 'click': Function.createDelegate(this, this._onFiltersMenuHandler) }, this);

    jqLast.append("<img src='/images/buttons/ArrowsUpDown.gif' style='margin:0px " + horMargin + "px' title='Clear Sort By' />");
    this.addHandlers(jqLast.children("img:last")[0], { 'click': Function.createDelegate(this, this._onSortBysMenuHandler) }, this);

    jqLast.append("<img src='/images/buttons/ShowOtherFields.gif' style='margin:0px " + horMargin + "px' title='Show All Fields' />");
    this.addHandlers(jqLast.children("img:last")[0], { 'click': Function.createDelegate(this, this._onOtherFieldsMenuHandler) }, this);

    if (this.get_canInsert()) {
      jqLast.append("<img src='/images/buttons/Add.gif' style='margin:0px " + horMargin + "px' title='Add Record' />");
      this.set_addNewRecordImg(jqLast.children("img:last")[0]);
      this.addHandlers(jqLast.children("img:last")[0], { 'click': Function.createDelegate(this, this._onAddRecordHandler) }, this);

      jqLast.append("<img src='/images/buttons/Accept.gif' style='margin:0px " + horMargin + "px' title='Insert new record' />");
      this.set_acceptNewRecordImg(jqLast.children("img:last")[0]);
      this.addHandlers(this._acceptNewRecordImg = jqLast.children("img:last")[0], { 'click': Function.createDelegate(this, this._onAddRecord_InsertHandler) }, this);

      jqLast.append("<img src='/images/buttons/Cross.gif' style='margin:0px " + horMargin + "px' title='Cancel new record' />");
      this.set_cancelNewRecordImg(jqLast.children("img:last")[0]);
      this.addHandlers(this._cancelNewRecordImg = jqLast.children("img:last")[0], { 'click': Function.createDelegate(this, this._onAddRecord_EndHandler) }, this);
    }
    jqLast.append("<img src='/images/Buttons/Excel.gif' style='margin:0px " + horMargin + "px' title='Export To Excel' />");
    this.addHandlers(jqLast.children("img:last")[0], { 'click': this.toExcel }, this);

    this._repaint();
    this.raiseEvent("onLoaded");
  },
  toExcel: function() {
    var filterExpressionLinq = escape(this._cleanUpFilter().toDynamicLinq());
    var columnsArray = [];
    for (var c = 0, cc = this.get_MTV().get_columns(); c < cc.length; c++)
      columnsArray.push(cc[c].get_uniqueName());
    var filterTemp = escape(!filterExpressionLinq.length && !this.get_filterTemp() ? this.get_filterTempDefault() : this.get_filterTemp());
    var columns = escape(columnsArray.join(","));
    var sortExpression = this.get_MTV().get_sortExpressions().toString();
    sortExpression = escape(sortExpression || this.get_MTV().get_clientDataKeyNames().join(","));

    location.href = "/Manager/webservices/common.asmx/ToExcel?EntityType=" + this.get_wsEntityType() +
    "&FilterLinq=" + filterExpressionLinq + "&FilterTemp=" + filterTemp +
    "&columns=" + columns + "&OrderBy=" + sortExpression;
  },
  _repaint: function() {
    if (this._filterRemoveImg) {
      this._filterRemoveImg.style.display = this._cleanUpFilter().toDynamicLinq() ? "" : "none";
      this._$refreshImg[0].style.display = this.get_inAjax() ? "none" : "";
      this._$refreshImgA[0].style.display = this.get_inAjax() ? "" : "none";
      if (this.get_canInsert()) {
        this.get_acceptNewRecordImg().style.display = this.get_cancelNewRecordImg().style.display = this.get_inEdit() ? "" : "none";
        this.get_addNewRecordImg().style.display = !this.get_inEdit() ? "" : "none";
      }
    }
  },
  _showLoadPanel: function() {
    this.set_inAjax(true);
    this._repaint();  //$J(this._showLoadPanel.$B).remove(); this._showLoadPanel.$B = $J.bubbleTip({ pos: { left: 0, top: 60 }, html: "this._inAjax(show):" + this._inAjax, pause: 5000 });
  },
  _hideLoadPanel: function() {    //$J(this._hideLoadPanel.$B).remove(); this._hideLoadPanel.$B = $J.bubbleTip({ pos: { left: 150, top: 60 }, html: "this._inAjax(hide):" + this._inAjax, pause: 5000 });
    this.set_inAjax(false);
    this._repaint();
  },

  dispose: function() {
    $J(this.get_otherFieldsMenu()).dialog("destroy");
    Dimok.Web.UI.RadGridBehavior.callBaseMethod(this, 'dispose');
  },
  _cleanUpFilter: function() {
    var filterExpressions = this.get_filterExpressions();
    for (var f = 0; f < filterExpressions.toList().length; ) {
      if (filterExpressions.toList()[f].FilterFunction == "NoFilter" ||
					filterExpressions.toList()[f].FilterFunction == "Contains" && filterExpressions.toList()[f].FilterValue == "")
        filterExpressions.remove(filterExpressions.toList()[f]);
      else f++;
    }
    return filterExpressions;
  },
  // Event delegates
  //  _onFocus: function(e) {
  //    if (this.get_element() && !this.get_element().disabled) {
  //      this.get_element().className = this._highlightCssClass;
  //    }
  //  },
  // *** Rows ***
  // *** ContextMenu
  get_metaField: function(uniqueName, propName) {
    var mf = Dimok.Accessorize(this.get_metaFields()[uniqueName]);
    if (mf) return propName ? mf["get_" + propName]() : mf;
    return null;
  },
  _onRowContextMenuHandler: function(sender, eventArgs) {
    var selectedItems = this.get_MTV().get_selectedItems();
    var srcelement = eventArgs.get_domEvent().rawEvent.srcElement;
    var cellIndex = srcelement.cellIndex || $J(srcelement).parents("TD:first")[0].cellIndex;
    var column = eventArgs._tableView.get_columns()[cellIndex];
    var gridDataItem = eventArgs.get_gridDataItem();
    if (!gridDataItem) return;
    var uniqueName = Object.capitalizeProperty(column.get_uniqueName(), gridDataItem.get_dataItem());
    Dimok.AddProperty(eventArgs, "_contextMenu", this.find_rowContextMenu());
    Dimok.AddProperty(eventArgs, "_keys", this.getGridDataItemKeys(gridDataItem));
    _showAllOrSelected.apply(this);
    _showOpen.apply(this);
    _showEdit.apply(this);
    _showAttach.apply(this);
    gridDataItem._dataFormatString = column._data.DataFormatString;
    this.set_contextMenuColumnUniqueName(uniqueName);
    this.set_contextMenuGridDataItem(gridDataItem);
    this.raise_rowContextMenuShowing(eventArgs);
    if (eventArgs.get_cancel()) return;
    if (this.find_rowContextMenu()) {
      var rcm = this.find_rowContextMenu();
      rcm.remove_itemClicked(this._onRowContextMenuItemClickedDelegate);
      rcm.add_itemClicked(this._onRowContextMenuItemClickedDelegate);
      rcm.show(eventArgs.get_domEvent());
      this.raise_rowContextMenuShowed(eventArgs);
    }
    // *** Locals ***
    function _showAllOrSelected() {
      var text = selectedItems.length ? "Selected" : "ALL";
      var DT_ATTR = "DefaultText";
      eventArgs.get_contextMenu().get_items().forEach(function(mi) {
        var miText = (mi.get_text().match(/(.+)&$/) || [])[1];
        if (miText) mi.get_attributes().setAttribute(DT_ATTR, miText);
        var dt = mi.get_attributes().getAttribute(DT_ATTR);
        if (dt) mi.set_text(dt + " " + text);
      });
    }
    function _showAttach() {
      var mi = this.find_rowContextMenu().findItemByValue("ShowDocs");
      if (!mi) return;
      //var loanID = eventArgs._gridDataItem.get_dataItem().LoanID;
      if (/*loanID && */this.get_canHaveDocs() && selectedItems.length == 1 && selectedItems[0] == gridDataItem) {
        mi.set_enabled(true);
        //Dimok.AddProperty(mi, "loanID", loanID);
      } else mi.set_enabled(false);
    }
    function _showOpen() {
      var miOpen = this.find_rowContextMenu().findItemByValue("Open");
      if (!miOpen) return;
      var loanID = eventArgs._gridDataItem.get_dataItem().LoanID;
      if (loanID) {
        miOpen.set_enabled(true);
        Dimok.AddProperty(miOpen, "loanID", loanID);
      } else miOpen.set_enabled(false);
    }
    function _showEdit() {
      var inEdit = srcelement.tagName == "INPUT";
      var isEdit = this.get_metaField(uniqueName, "IsEdit");
      var isEditAll = this.get_metaField(uniqueName, "IsEditAll");
      var miEdit = this.find_rowContextMenu().findItemByValue("Edit");
      var isEnabled = isEdit && !inEdit && (!!selectedItems.length || isEditAll);
      if (isEnabled && selectedItems.length) isEnabled = Array.contains(selectedItems, gridDataItem);
      miEdit.set_enabled(isEnabled);
      if (miEdit.get_enabled()) {
        miEdit.set_text(selectedItems.length ? "Edit Selected" : "Edit Whole List");
      } else miEdit.set_text("Edit");
      Dimok.AddProperty(miEdit, "_editAll", !selectedItems.length && isEditAll);
    }
  },
  _onRowContextMenuItemClicked: function(sender, eventArgs) {
    if (!eventArgs.get_targetElement()) return;
    Dimok$AddProperty(eventArgs, "_GridDataItem", this.get_contextMenuGridDataItem());
    Dimok$AddProperty(eventArgs, "_UniqueName", this.get_contextMenuColumnUniqueName());
    Dimok$AddProperty(eventArgs, "_EditType", Dimok.Accessorize(this.get_metaFields()[eventArgs.get_UniqueName()]));
    Dimok.AddProperty(eventArgs, "_keys", this.getGridDataItemKeys(this.get_contextMenuGridDataItem()));
    Dimok.Accessorize(eventArgs);
    eventArgs.addCancel();
    this.raise_rowContextMenuItemClicked(eventArgs);
    if (!eventArgs.get_cancel())
      this._onRowContextMenuItemClickedLocal(sender, eventArgs);
    sender.close();
  },
  _onRowContextMenuItemClickedLocal: function(sender, eventArgs) {
    switch (eventArgs._item.get_value()) {
      case "Open":
        showApplInfo(eventArgs.get_item().get_loanID());
        break;
      case "Edit":
        this._inLineEdit_Start(eventArgs.get_targetElement(),
          Dimok.Accessorize(
            { type: Dimok.Templates.toString(eventArgs.get_EditType().get_Template()),
              event: eventArgs.get_EditType().get_EditEvent(),
              submit: "OK",
              cssclass: "inLine",
              style: "margin 0px",
              _template: eventArgs.get_EditType(),
              _fieldUpdate: eventArgs.get_EditType().get_LookUpFieldName() || eventArgs.get_UniqueName(),
              _fieldReturn: eventArgs.get_UniqueName(),
              _entityType: this.get_wsEntityType(),
              _filterLinqs: _filterLinqs.apply(this, [eventArgs.get_GridDataItem().get_dataItem()]),
              _gridDataItem: eventArgs.get_GridDataItem(),
              _elementCss: { margin: "0 px" },
              _wsObject: WSA,
              _editAll: eventArgs.get_item().get_editAll()
            }
          )
        );
        break;
      case "Insert":
        break;
    }
    function _filterLinqs(dataItem) {
      var filterLinqs = [];
      Array.forEach(this.get_masterTableView().get_clientDataKeyNames(), function(key) {
        filterLinqs.push(key + "=" + dataItem[key]);
      });
      return filterLinqs;
    }
  },
  _inLineEdit_Start: function(jqSelector, editSettings) {
    //    var grid = this.get_grid();
    //    var kn = grid.ClientSettings && grid.ClientSettings.AllowKeyboardNavigation;
    //    if (kn) grid.ClientSettings.AllowKeyboardNavigation = false;
    //    editSettings.callback = function() { if (kn) grid.ClientSettings.AllowKeyboardNavigation = true; }
    $J(jqSelector).editable(Function.createCallback(this._inLineEdit_Update(), this), editSettings).trigger(editSettings.get_event());
  },
  _inLineEdit_Update: function() {
    return function(value, settings, rgbContext) {
      if (settings.get_editAll()) rgbContext.set_batchKeys(rgbContext.getKeysByFilter());
      else rgbContext.set_batchKeys(rgbContext.getGridDataItemsKeys());
      rgbContext._inLineUpdate.apply(rgbContext, [settings.get_fieldUpdate(), value]);
      return;
      var params = [rgbContext.get_entityType(), rgbContext.getGridDataItemKeys(settings.get_gridDataItem(), true),
                    settings.get_fieldUpdate(), value];
      return Dimok.Ajax({ methodName: "GetList_Update", wsObject: WSA }, params, _success);
      function _success(json) {
        var result = json.d[0];
        var gdi = settings.get_gridDataItem();
        var di = gdi.get_dataItem();
        var tv = gdi.get_owner();
        for (var f in result) {
          di[f] = result[f];
          var cell = tv.getCellByColumnUniqueName(gdi, f);
          if (!cell) continue;
          var column = tv.getColumnByUniqueName(f);
          if (!column) continue;
          cell.innerHTML = String.format(column._data.DataFormatString || "{0}", di[f]);
        }
        $J(".bubble").bubbleTip({ html: "Updated.", pause: 2000, element: tv.getCellByColumnUniqueName(gdi, settings.get_fieldReturn()) });
        return String.format(settings._formatString || "{0}", result[settings._fieldReturn]);
      }
    }
  },
  _getListUpdateMethos: function(entityType, keys, fieldName, fieldValue, onSuccess, onError) {
    return Dimok.FindWSMethod("GetList_Update", WSA)(entityType, keys, fieldName, fieldValue, onSuccess, onError);
  },
  _inLineUpdate: function(fieldName, fieldValue, isBatch) {
    if (isBatch === undefined) { this._showLoadPanel(); isBatch = this.get_batchKeys().length > 1; }
    var keys = Dimok.$A(this.get_batchKeys().shift());
    var keysString = Sys.Serialization.JavaScriptSerializer.serialize(keys);
    var gdi = this.findGridDataItem(keys) || undefined;
    if (!keys) return this._hideLoadPanel();
    this._getListUpdateMethos(this.get_wsEntityType(), keys, fieldName, fieldValue,
      Function.createDelegate(this, _onSuccess), Function.createDelegate(this, _onError));
    function _onSuccess(result) {
      if (gdi) this.bindRow(result[0], gdi);
      _onComplete.apply(this, [{ html: keysString + "." + this.get_batchKeys().length + " left.", topFly: 0}]);
    }
    function _onError(result) {
      _onComplete.apply(this, [{ error: keysString + '\n' + result.get_message()}]);
    }
    function _onComplete(bubbleSettings) {
      var tipElement = (gdi || this.get_grid()).get_element();
      if (isBatch && gdi) gdi.set_selected(false);
      $J.bubbleTip($J.extend({ element: tipElement }, bubbleSettings));
      if (this.get_batchKeys().length)
        return setTimeout(Function.createDelegate(this, function() { this._inLineUpdate(fieldName, fieldValue, isBatch) }), 10);
      this._hideLoadPanel();
      if (isBatch) {
        this.clearSelected();
        $J.bubbleTip({ element: this.get_grid().get_element(), html: "Price Batch completed.", flash: true, callback: Function.createDelegate(this, this.rebind) });
      }
    }
  },
  _getCarPrice: function(bookValueTypeID, isBatch) {
  },
  _onAddRecord_InsertHandler: function() {
    var mtv = this.get_masterTableView();
    var gridDataItem = mtv.get_dataItems()[mtv.get_dataSource().length - 1];
    var inputs = $J("input,select", gridDataItem.get_element());
    var newRecord = {};
    Array.forEach(mtv.get_columns(), function(column) {
      var un = column.get_uniqueName();
      var td = mtv.getCellByColumnUniqueName(gridDataItem, un);
      var control = $J("input,select,textarea", td);
      if (control.val()) newRecord[this.get_metaField(un, "LookUpFieldName") || un] = control.val();
    }, this);
    $J.extend(newRecord, this.get_detailKeys());
    if (!confirm(Sys.Serialization.JavaScriptSerializer.serialize(newRecord))) return;
    var ret = Dimok.Ajax({ methodName: "GetList_Insert", wsObject: WSA }, [this.get_wsEntityType(), newRecord]);
    if (!ret) return;
    this.set_insertedRecord(ret);
    this._onAddRecord_EndHandler();
  },
  _onAddRecord_EndHandler: function() {
    this.set_inEdit(false);
    var tr = this.get_MTV().get_dataItems()[this.get_MTV().get_dataSource().length - 1].get_element();
    $J("td", tr).empty();
    this.get_MTV().rebind();
  },
  _onAddRecordHandler: function() {
    var mtv = this.get_masterTableView();
    var dataSource = mtv.get_dataSource();
    var ret = Dimok.Ajax({ methodName: "GetList_DefaultEntity", wsObject: WSA }, [this.get_wsEntityType()]);
    Array.add(dataSource, ret);
    mtv.dataBind();
    this.set_inEdit(true);
    var gridDataItem = mtv.get_dataItems()[dataSource.length - 1];
    //$J("td", gridDataItem.get_element()).html("&nbsp;");
    //  for (var un in this.get_metaFields().propNames()) {
    Object.forEach(this.get_metaFields(), function(et, un) {
      var td = mtv.getCellByColumnUniqueName(gridDataItem, un);
      if (td && this.get_metaField(un, "IsAdd")) {
        var settings = {
          type: et.get_Template(),
          event: et.get_EditEvent(),
          style: "margin 0px",
          _template: et,
          _fieldUpdate: et.get_LookUpFieldName() || un,
          _fieldReturn: un,
          _gridDataItem: gridDataItem,
          _elementCss: et.get_ElementCss(),
          _wsObject: WSA
        }
        Dimok$BuildTemplate(td, settings);
      }
    }, this, true);
    $J("input:first", gridDataItem.get_element()).focus();
    $J("input:not(:last)", gridDataItem.get_element()).keydown(doEnterKey);
    $J("input:last", gridDataItem.get_element()).keydown(Function.createDelegate(this, function() {
      if (event.keyCode == 13) this._onAddRecord_InsertHandler();
    }));
    this._repaint();
  },

  _goToPage: function(sender, args) {
    args.set_cancel(true);
    this.get_masterTableView().page(Math.min(sender._maxValue, args._newValue));
  },
  // *** Coulumns ***
  _saveColumnsList: function(list, callBack) {
    if (!list) {
      list = [];
      for (var c = 0, cc = this.get_masterTableView().get_columns(); c < cc.length; c++)
        list.push(cc[c].get_uniqueName());
    }
    Dimok.FindWSMethod("RadGrid_SetColumns", WSA)(list, this.get_pageType(), this.get_profileID(), this.get_currentReport(), callBack || null, this.get_wsErrorDelegate());
  },
  _columnsChanged: function(sender, args) {
    if (args._item.get_value() == "0") return;
    var divBridgeColumns = $J(this.find_columnsMenu()._findItemByText("Columns").get_element()).find("#divBridgeColumns")[0];
    var checks = divBridgeColumns.all.tags("INPUT");
    for (var c = 0, list = []; c < checks.length; c++)
      if (checks[c].checked) list.push(checks[c]["DataField"]);
    this._saveColumnsList(list, _cb);
    function _cb(result) {
      if (confirm("Reload page to see new settings.")) location.reload();
    }
  },
  _columnsSwapped: function(sender, args) {
    clearTimeout(arguments.callee.procid);
    arguments.callee.procid = setTimeout(
      Function.createDelegate(this, function() { this._saveColumnsList(null, _cb) }), 300);
    function _cb(result) {
      if (confirm("Reload page to see new settings.")) location.reload();
    }
  },
  _onColumnsMenuHandler: function(sender, args) {
    this.find_columnsMenu().show(args.get_domEvent());
  },
  // *** Filter ***
  _clearFilter: function(uniqueName) {
    var tv = this.get_masterTableView();
    (this._getFilterTextBox(uniqueName) || {}).value = '';
    var column = tv.getColumnByUniqueName(uniqueName);
    if (column) {
      column._data.CurrentFilterFunction = 0;
      column._data.CurrentFilterFunctionName = "NoFilter";
    }
    var filters = tv.get_filterExpressions();
    filters.remove(filters.find(uniqueName));
  },
  _clearFilters: function() {
    var tv = this.get_masterTableView();
    var fltrList = this.get_filterExpressions().toList();
    while (fltrList.length > 0)
      this._clearFilter(fltrList[0].get_columnUniqueName());
    tv.rebind();
  },
  _getFilterTextBox: function(columnUniqueName) {
    var tv = this.get_masterTableView();
    var row = tv._getTableFilterRow();
    var cellIndex = tv._getCellIndexByColumnUniqueNameFromTableRowElement(row, columnUniqueName);
    return cellIndex == null ? null : row.cells[cellIndex].getElementsByTagName("input")[0];

  },
  _onFiltersMenuHandler: function(ev) {
    var filterExps = this._cleanUpFilter();
    if (!this._filtersMenuTable) this._filtersMenuTable = $J("#tblFilterColumns", this.find_filtersMenu().get_element())[0];
    var tbl = this._filtersMenuTable;
    while (tbl.rows.length > 1) tbl.deleteRow(tbl.rows.lenght);
    tbl.rows[0].style.display = "none";
    var mtv = this.get_masterTableView();
    Array.forEach(filterExps._array, function(filter) {
      var row = tbl.insertRow();
      var uniqueName = filter.get_columnUniqueName();
      var column = mtv.getColumnByUniqueName(uniqueName);
      $J(row.insertCell()).append("<input type='checkbox' id='chk" + uniqueName + "' checked UniqueName='" + uniqueName + "'></input>");
      $J(row.insertCell()).html(
        "<label for='chk" + uniqueName + "'>" +
          filter.toDynamicLinq().replace(new RegExp(uniqueName, "g"), (column || filter).HeaderText) +
        "</label>"
      ).attr("noWrap", true);
    });
    this.find_filtersMenu().show(ev);
  },
  _filtersChanged: function(sender, args) {
    if (args._item.get_value() == "0") return this._clearFilters();
    var tbl = this._filtersMenuTable;
    var This = this;
    $J(tbl).find("input:not(:checked)").each(function() {
      This._clearFilter(this.UniqueName);
    });
    //    var unChecked = $J(tbl).find("input:not(:checked)").get();
    //    for (var chk in unChecked)
    //      this._clearFilter(unChecked[chk].UniqueName);
    this.get_masterTableView().rebind();
  },
  // *** OtherFields ***
  _onOtherFieldsMenuHandler: function(ev) {
    var This = this;
    var dim = this._detailViewDimensions;
    var jq = $J(this.get_otherFieldsMenu());
    if (jq.dialog("isOpen")) return jq.dialog("close");
    if (!this._jqdOtherFields || this._jqdOtherFields && this.get_otherFieldsMenu().dragged) {
      $J(this.get_otherFieldsMenu()).dialog("destroy");
      this.get_otherFieldsMenu().dragged = false;
      this._jqdOtherFields =
      $J(this.get_otherFieldsMenu()).dialog({
        height: dim.h || 200,
        width: dim.w || 200,
        position: [dim.x || $J(ev.target).offset().left, dim.y || $J(ev.target).offset().top],
        resize: function() {
          //$J(this).children("div").height($J(this).height() - 1);
          $J(this).children("div").height($J(this).parent()[0].style.pixelHeight - $J(this).parent().children()[0].offsetHeight * 2);
          $J(this).children("div").width($J(this).parent()[0].style.pixelWidth - 30);
        },
        resizeStop: _saveDialogDimensions,
        dragStop: function(type, data) { this.dragged = true; _saveDialogDimensions(type, data); }
      });
      this.get_otherFieldsMenu().style.display = "";
      function _saveDialogDimensions(type, data) {
        var dim = This._detailViewDimensions;
        dim.x = data.position.left; dim.y = data.position.top;
        if (data.size) { dim.w = data.size.width; dim.h = data.size.height; }
        Dimok.FindWSMethod("SetBridgeDetailView", WSA)(dim, This.get_pageType(), This.get_profileID(), This.get_currentReport(), null, This.get_wsErrorDelegate());
      }
      this._jqdOtherFields.find("ul").sortable({
        stop: function(e, ui) {
          var dict = {};
          $J(this).find("[DataField]").each(function(i) {
            dict[this.DataField] = i;
          });
          Dimok.FindWSMethod("SetBridgeDetailColumns", WSA)(dict, This.get_pageType(), This.get_profileID(), This.get_currentReport(), null, This.get_wsErrorDelegate());
        }
      });
    } else jq.dialog("open");
  },
  _otherFields_DataBind: function(gridDataItem) {
    if (!gridDataItem) return;
    var dataItem = gridDataItem.get_dataItem();
    if (!this._jqdOtherFields || !this._jqdOtherFields.dialog("isOpen")) return;
    this._jqdOtherFields.find("ul [DataField]").each(function() {
      this.innerHTML = this.DataFormatString ? String.localeFormat(this.DataFormatString, dataItem[this.DataField]) : dataItem[this.DataField];
    });
  },

  // *** SortBy ***
  _onSortBysMenuHandler: function(ev) {
    var mtv = this.get_masterTableView();
    var sortExps = mtv.get_sortExpressions();
    if (!this._sortBysMenuTable) this._sortBysMenuTable = $J("#tblSortByColumns", this.find_sortBysMenu().get_element())[0];
    if (!this._sortBysMenuTable) return alert("Unable to find SortBy Menu Table.");
    var tbl = this._sortBysMenuTable;
    $J(tbl).sortable("destroy");
    $J(tbl).html("");
    Array.forEach(sortExps._array, function(sortBy) {
      var fieldName = sortBy.get_fieldName();
      var column = _getColumnByDataField(mtv.get_columns(), fieldName);
      $J(tbl).append("<li><input type='checkbox' id='chk_" + fieldName + "' checked FieldName='" + fieldName + "' /><label for='chk" + fieldName + "'>" + (column || sortBy).HeaderText + ["", " ASC", " DESC"][sortBy.get_sortOrder()] + "</label></li>");
    });
    $J(tbl).sortable({
      stop: Function.createDelegate(this, this._sortBysResorted)
    });
    this.find_sortBysMenu().show(ev);
    function _getColumnByDataField(columns, dataField) {
      for (var c = 0; c < columns.length; c++)
        if (columns[c]._data.DataField == dataField) return columns[c];
      return null;
    }
  },
  _sortBysResorted: function() {
    var mtv = this.get_masterTableView();
    var sortExps = mtv.get_sortExpressions();
    var tbl = this._sortBysMenuTable;
    $J(tbl).find("input:checked").each(function(i) {
      mtv.get_sortExpressions().find(this.FieldName).SortIndex = i;
    });
    sortExps._array.sort(function(s1, s2) { return s1.SortIndex < s2.SortIndex ? -1 : s1.SortIndex == s2.SortIndex ? 0 : 1 });
    mtv.rebind();
  },
  _sortBysChanged: function(sender, args) {
    var checkBoxFilter = args._item.get_value() == "0" ? ":checked" : ":not(:checked)";
    var tbl = this._sortBysMenuTable;
    //    var unChecked = $J(tbl).find("input" + checkBoxFilter).get();
    var mtv = this.get_masterTableView();
    $J(tbl).find("input" + checkBoxFilter).each(function() {
      mtv.get_sortExpressions().find(this.FieldName).set_sortOrder(2);
      mtv.sort(this.FieldName);
    });
    //    for (var chk in unChecked) {
    //      mtv.get_sortExpressions().find(unChecked[chk].FieldName).set_sortOrder(2);
    //      mtv.sort(unChecked[chk].FieldName);
    //    }
    this.get_masterTableView().rebind();
  },
  showReport: function(reportName, callBack) {
    Dimok.FindWSMethod("RadGrid_Report_Copy", WSA)(this.get_pageType(), this.get_profileID(), reportName, "", _cb, this.get_wsErrorDelegate());
    function _cb() {
      if (callBack) callBack();
    }
  },
  saveReport: function(filterName, callBack) {
    this.set_currentReport(filterName);
    this.get_masterTableView().rebind();
    var ev = new Sys.EventArgs();
    ev.ReportName = filterName;
    if (callBack) callBack(ev);
  },
  deleteReport: function(filterName, callBack) {
    Dimok.FindWSMethod("RadGrid_Report_Delete", WSA)(this.get_pageType(), this.get_profileID(), filterName,
    Function.createDelegate(this, _cb), this.get_wsErrorDelegate());
    function _cb(result) {
      var ev = new Sys.EventArgs();
      ev.ReportName = filterName;
      if (callBack) callBack(ev);
    }
  },
  _decorateFilters: function() {
    var columns = this.get_masterTableView().get_columns();
    for (var i = 0; i < columns.length; i++) {
      var box = this._getFilterTextBox(columns[i].get_uniqueName());
      if (!box || box.type != "text") continue;
      box.value = String.format(Dimok.Web.UI.RadGridBehavior.filterFormat(columns[i]._data.CurrentFilterFunction), box.value);
    }
  },
  setCaption: function(command) {
    command = command ? "[Cmd:" + command + "]" : "";
    var tableView = this.get_masterTableView();
    var sort = tableView.get_sortExpressions() + "" ? "[Sort:" + tableView.get_sortExpressions() + "]" : "";
    var filter = tableView.get_filterExpressions().toDynamicLinq();
    if (filter) filter = "[Filter:" + filter.replace(/DateTime.Parse/ig, "") + "]";
    if (this.get_filterTemp()) filter += "{" + this.get_filterTemp + "}";
    (tableView.get_element().caption || "").innerHTML = command + filter + sort;
  },
  clickGridDataItem: function(gridDataItem, eventExtender) {
    if (gridDataItem)
      this.clickRow(gridDataItem.get_element(), eventExtender);
  },
  clickRow: function(row, eventExtender) {
    var eventSubj = $J.extend(document.createEventObject(), eventExtender || {});
    //eventSubj.ctrlKey = true; eventSubj.keyCode = 70;
    row.fireEvent('onclick', eventSubj); // likewise 'onkeypress'; keyCode=6; which appears to be too late to invoke Ctrl-F-find-on-page.  

  },
  onChangePageSize: function(sender, args) {
    args.set_cancel(true);
    this.get_masterTableView().set_pageSize(sender.get_value());
    event.cancelBubble = true;
    return false;
  },

  // Ajax
  _setMaxPage: function() {
    var grid = this.get_grid();
    var pagerCurrent = this.get_goToPageBox();
    var masterTableView = this.get_masterTableView();
    var pageCount = Math.ceil(masterTableView.get_virtualItemCount() / masterTableView.get_pageSize());
    masterTableView.PageCount = pageCount;
    pagerCurrent.set_maxValue(pageCount);
    if (pagerCurrent.get_value() > pagerCurrent.get_maxValue())
      pagerCurrent.set_value(pagerCurrent.get_maxValue());
    if (this.get_pageCountLabel()) this.get_pageCountLabel().innerHTML = pageCount;
  },
  // Behavior properties
  get_executor: function(path) { return this._executor[path]; },
  set_executor: function(path, v) {
    //if (this._executor[path]) this._executor[path].abort();
    return this._executor[path] = v;
  },
  get_executorLast: function() { return this._executorLast; },
  set_executorLast: function(path, v) {
    this.set_executor(path, v);
    return this._executorLast = { path: path, executor: v };
  },
  set_cancelAjax: function(v) {
    this._cancelAjax = v;
    if (!v) return;
    this._abortExecutor();
  },
  get_inAjax: function(v) {
    return this._inAjax > 0;
  },
  set_inAjax: function(v) {
    this._inAjax = (this._inAjax || 0) + (v ? 1 : -1);
    if (this._inAjax < 0) { alert("Ajax count is negative."); }
    this._inAjax = Math.max(0, this._inAjax);
    return this._inAjax;
  },
  set_ajaxTimeStamp: function(methodName) {
    var path = this.get_id() + ":" + methodName;
    this._ajaxTimeStamp[path] = new Date().valueOf();
    return this._ajaxTimeStamp[path];
  },
  get_ajaxTimeStamp: function(methodName) {
    var path = this.get_id() + ":" + methodName;
    if (!this._ajaxTimeStamp[path]) throw "Uninitialized use of " + path + " time stamp.";
    return this._ajaxTimeStamp[path];
  },
  _ajaxCount: {},
  push_ajaxCount: function(methodName) {
    var path = this.get_id() + ":" + methodName;
    return this._ajaxCount[path] = (this._ajaxCount[path] || 0) + 1;
  },
  shift_ajaxCount: function(methodName) {
    var path = this.get_id() + ":" + methodName;
    return this._ajaxCount[path] = Math.max(0, (this._ajaxCount[path] || 0) - 1);
  },
  set_batchKeys: function(batchKeys) {
    if (batchKeys && Object.getType(batchKeys) == Boolean) {
      batchKeys = this.getGridDataItemsKeys();
      if (!batchKeys.length) batchKeys = this.getKeysByFilter();
      return this.set_batchKeys(batchKeys);
    }
    var e = Function._validateParams(arguments, [{ name: "batchKeys", type: Array, mayBeNull: false, optional: true}]); if (e) throw e;
    if (arguments.length && this.get_batchKeys().length) throw "Can not assign to Batch Key array that is not empty.";
    return this._batchKeys = batchKeys || [];
  },
  get_pageCountLabelID: function() { return this._pageCountLabelID; }, set_pageCountLabelID: function(value) { this._pageCountLabelID = value; },
  get_goToPageBoxID: function() { return this._goToPageBoxID; }, set_goToPageBoxID: function(value) { this._goToPageBoxID = value; },
  get_pageSizeBoxID: function() { return this._pageSizeBoxID; }, set_pageSizeBoxID: function(value) { this._pageSizeBoxID = value; },
  get_filterTemp: function() {
    var keys = [];
    if (this._filterTemp) keys.push(this._filterTemp);
    for (var n in this._filterTempKeys)
      keys.push(n + "=" + this._filterTempKeys[n]);
    return keys.join(" && ");
  },
  set_filterTemp: function(v) {
    if (arguments.length > 1) {
      if (!this._filterTempKeys) this._filterTempKeys = {};
      var name = arguments[0];
      if (name === undefined) this._filterTempKeys = {};
      else {
        if (Object.getType(name) == String) {
          var val = arguments[1];
          if (val === undefined) delete this._filterTempKeys[name];
          else this._filterTempKeys[name] = val;
        } else if (Object.getType(name) == Array) {
          var vals = arguments[1];
          Array.forEach(name, function(n, i) {
            this._filterTempKeys[n] = vals[i];
          }, this);
        } else throw "Parameter v is of unknown type:" + Object.getType(v);
      }
    } else {
      if (v == null || Object.getType(v) == Object) { this._filterTempKeys = v; this._filterTemp = ""; }
      else { this._filterTemp = v; this._filterTempKeys = {}; }
    }
    this.get_goToPageBox().set_maxValue(1);
    var mtv = this.get_masterTableView();
    if (mtv.get_currentPageIndex() === 0) mtv.set_currentPageIndex(1, true)
    mtv.set_currentPageIndex(0);
  },
  get_wsMethodName: function() { return this._wsMethodName; }, set_wsMethodName: function(v) { this._wsMethodName = v; },
  get_wsMethodName_SetActiveRow: function() { return this._wsMethodName_SetActiveRow || this._wsMethodName + "_SetActiveRow"; },
  set_wsMethodName_SetActiveRow: function(v) { this._wsMethodName_SetActiveRow = v; },
  get_wsMethodName_Count: function() { return this._wsMethodName_Count || this._wsMethodName + "_Count"; },
  set_wsMethodName_Count: function(v) { this._wsMethodName_Count = v; },
  get_wsMethodName_Delete: function() { return this._wsMethodName_Delete || this._wsMethodName + "_Delete"; },
  set_wsMethodName_Delete: function(v) { this._wsMethodName_Delete = v; },
  get_wsMethodName_Details: function() { return this._wsMethodName_Details || this._wsMethodName + "_Details"; },
  set_wsMethodName_Details: function(v) { this._wsMethodName_Details = v; },

  // grid objects
  find_grid: function() { return $find(this.get_element().id); },
  get_masterTableView: function() { return this.find_grid().get_masterTableView(); },
  get_filterExpressions: function() { return this.get_masterTableView().get_filterExpressions(); },
  get_pageSizeBox: function() { return $find(this._pageSizeBoxID); },
  get_goToPageBox: function() { return $find(this._goToPageBoxID); },
  get_pageCountLabel: function() { return $get(this._pageCountLabelID); },

  // Events
  add_onLoaded: function(handler) { this.get_events().addHandler('onLoaded', handler); },
  remove_onLoaded: function(handler) { this.get_events().removeHandler('onLoaded', handler); }
}

Dimok.Web.UI.RadGridBehavior.registerClass('Dimok.Web.UI.RadGridBehavior', motobankcorp.UI.Behavior);
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();